﻿;
function checkRestrictive() {
    return (pageData.settings['restrictive'] == "1" ? true: false)
};
function setHistory() {
    var layoutEl = pageLayout.children().clone(true);
    $HASH['history'].push({
        layout: layoutEl,
        skin: pageBody.find('#skinLink').data('href') || pageBody.find('#skinLink').attr('href'),
        pageData: $.extend(true, {},
        pageData),
        currentToolsId: currentToolsId
    });
    if ($HASH['history'].length > top.pageSetHistory) {
        $HASH['history'].shift()
    };
    $HASH.historyNum = $HASH['history'].length - 1;
    if ($HASH.historyNum > 0) {
        undoBtn.addClass('active')
    }
};
function undo() {
    if ($HASH.historyNum > 0) {
        $HASH.historyNum--;
        if ($HASH.historyNum == 0) {
            undoBtn.removeClass('active')
        };
        redoBtn.addClass('active');
        resetPageData()
    }
};
function redo() {
    if ($HASH.historyNum < $HASH['history'].length - 1) {
        $HASH.historyNum++;
        if ($HASH.historyNum == $HASH['history'].length - 1) {
            redoBtn.removeClass('active')
        };
        undoBtn.addClass('active');
        resetPageData()
    }
};
function resetPageData() {
    clearTips(toolsMain);
    elToolsPanel.hide();
    pageData = $.extend(true, {},
    $HASH['history'][$HASH.historyNum]['pageData']);
    pageLayout.empty().append($HASH['history'][$HASH.historyNum]['layout'].clone(true));
    if (pageBody.find('#skinLink').data('href') != $HASH['history'][$HASH.historyNum]['skin']) {
        resetPageSkin($HASH['history'][$HASH.historyNum]['skin'])
    };
    var cid = $HASH['history'][$HASH.historyNum]['currentToolsId'],
    noSetTools = 0;
    if (cid == currentToolsId) {
        noSetTools = 1
    };
    if (cid == 'body') {
        selectedBody(noSetTools)
    } else {
        selectElTools($('#' + cid, pageLayout), 1, noSetTools)
    };
    change('do');
    $HASH['iframeObj'].reloadResponsiveImage();
    $HASH['iframeObj'].resizeScroll()
};
function change(key) {
    $HASH['change']['state'] = true;
    if (key == 'do' || key == 'all') {
        $HASH['change']['data'] = {
            pageData: $.extend(true, {},
            pageData),
            layout: getPageLayout()
        }
    } else if (key == 'pageData') {
        $HASH['change']['data']['pageData'] = $.extend(true, {},
        pageData)
    } else {
        $HASH['change']['data']['layout'] = getPageLayout()
    };
    activeSave();
    if (key != 'do') {
        redoBtn.removeClass('active');
        if ($HASH.historyNum != $HASH['history'].length - 1) {
            for (i = $HASH['history'].length - 1; i > $HASH.historyNum; i--) {
                $HASH['history'].pop()
            }
        };
        setHistory()
    }
};
function clearChange() {
    $HASH['change'] = {
        "state": false,
        "data": {}
    };
    clearSave()
};
function activeSave() {
    top.setSave(pageId, 1, 
    function(callBack) {
        save(callBack)
    });
    saveBtn.addClass('active')
};
function clearSave() {
    top.setSave(pageId, 0);
    saveBtn.removeClass('active')
};
function save(callBack) {
    if (!$HASH['change']['state']) return;
    var fn = function() {
        var data = {
            pageId: pageId,
            data: $HASH['change']['data']
        };
        rpcJSON('save', data, 
        function(backData) {
            clearChange();
            Tips('success', '保存成功');
            fireHandler(callBack)
        })
    };
    fn()
};
function getPageLayout() {
    var layoutTemp = pageLayout.clone(true);
    layoutTemp.find('script').remove();
    layoutTemp.find('div[path],header[path],footer[path]').removeClass('currentTools selectedTools');
    layoutTemp.find('div.row-fluid').removeClass('ui-draggable ui-resizable');
    layoutTemp.find('img.responsiveImage').attr('src', lazyLoadSrc);
    layoutTemp.find('ul.setPhoneDropMenu').removeClass('setPhoneDropMenu');
    layoutTemp.find('div.appWrapper[data-content="json"]').each(function(i, item) {
        var data = $(this).data('data');
        data.elId = $(this).attr('id');
        if ($(this).data('events')) {
            data.events = $(this).data('events')
        };
        var str = '<!--' + $.toJSON(data) + '-->';
        replaceApp($(this), str)
    });
    layoutTemp.find('div[role="dragEmptyEl"]').remove();
    layoutTemp.find('img[lazyload="1"]').attr('src', lazyLoadSrc);
    if (pageData.settings.header != '1') {
        var headerHtml = layoutTemp.find('#header').html();
        headerHtml = '<hide_header><header id="header" style="display:none;">' + headerHtml + '</header></hide_header>';
        layoutTemp.find('#header').replaceWith(headerHtml)
    };
    if (pageData.settings.footer != '1') {
        var footerHtml = layoutTemp.find('#footer').html();
        footerHtml = '<hide_footer><footer id="footer" style="display:none;">' + footerHtml + '</footer></hide_footer>';
        layoutTemp.find('#footer').replaceWith(footerHtml)
    };
    return (layoutTemp.html())
};
function checkAppWrapper(el, app) {
    var flag = true;
    if (el.data('appid')) {
        if (el.data('appid') != app.data('data')['id']) {
            var type = app.data('data')['type'] == 'app' ? '应用': '组件';
            Tips('error', type + '与容器不匹配，不能被放置！');
            flag = false
        }
    };
    return flag
};
function checkSole(app) {
    var flag = true;
    if (app.data('data')['sole'] == '1' && pageBody.find('div.appWrapper[data-appid="' + app.data('data')['id'] + '"]').length) {
        Tips('error', '本页面只允许放置一个该应用！');
        flag = false
    };
    return flag
};
function insertApp(el, data) {
    $HASH['iframeObj'].replaceApp(el, change)
};
function loadDropApp(appEl, placeholder) {
    var loadingEl = appEl.clone(true).insertBefore(placeholder).append('<div class="module_loading"></div>').addClass('module_loading_box'),
    appId = appEl.data('data')['id'],
    type = appEl.data('data')['type'];
    getApp({
        appId: appId,
        type: type
    },
    function(backData) {
        insertApp(loadingEl)
    },
    function() {
        loadingEl.remove();
        Tips('error', '加载出错，请重试！')
    })
};
function reloadApp(app, callBack, flag) {
    if (typeof app == 'string') {
        app = $('#' + app, pageLayout)
    };
    if (!app.length) return;
    var id = app.attr('id'),
    data = app.data('data'),
    loadingEl = $('<div class="module_loading_box custom_module_box "><p class="custom_module_name">' + data['name'] + '</p><div class="module_loading"></div></div>'),
    styleEl,
    events;
    if (app.find('>div[data-styles]').length) {
        styleEl = app.find('>div[data-styles]').clone(true)
    };
    if (app.data('events')) {
        data.events = app.data('events')
    };
    app.empty().append(loadingEl);
    data.appId = data.id;
    data.elId = id;
    getApp(data, 
    function(backData) {
        $HASH['iframeObj'].replaceApp(app, 
        function() {
            var newApp = $('#' + id, pageLayout);
            if (styleEl) {
                styleEl.prependTo(newApp)
            };
            if ($.isFunction(callBack)) {
                callBack()
            };
            if (currentToolsId == id) {
                selectedTools = newApp;
                currentTools = newApp;
                newApp.addClass('selectedTools currentTools')
            }
        })
    },
    function() {
        loadingEl.remove();
        Tips('error', '加载出错，请重试！')
    })
};
function getEmptyRow() {
    return $('<div class="row"  role="dragEl"  path="row"><div class="rowPatch"><div class="span12"><div class="boxBlock"></div></div></div></div>')
};
function getEmptyEl() {
    return ('<div role="dragEmptyEl" style="padding:10px;">拖放插件到这里</div>')
};
function getSpanNum(span) {
    if (!span.attr('class')) return;
    return parseInt(span.attr('class').replace('active', '').replace('span', ''))
};
function replaceId(el) {
    if ($('#' + el.attr('id'), pageLayout).length) {
        var oldId = el.attr('id'),
        newId = 'el_' + getNewId();
        el.attr('id', newId);
        if ($('#' + oldId + '_style', el).length) {
            var styleEl = $('#' + oldId + '_style', el);
            replaceStyleId(styleEl, oldId, newId)
        }
    }
};
function replaceStyleId(styleEl, oldId, newId) {
    var reg = new RegExp(oldId, "g"),
    newhtml = styleEl.html().replace(reg, newId);
    styleEl.attr('id', newId + '_style').html(newhtml)
};
function getPasteData() {
    var data = $.extend(true, {},
    top.$HASH['pasteData']['data'].clone(true)),
    id = data.attr('id'),
    soleApp = [];
    if (data.attr('static')) {
        if ($('#' + id, pageLayout).length) {
            $('#' + id, pageLayout).remove()
        };
        if ($('#' + id + '_style', pageLayout).length) {
            $('#' + id + '_style', pageLayout).remove()
        }
    };
    replaceId(data);
    $('div[path][id]', data).each(function() {
        replaceId($(this));
        if ($(this).data('data') && $(this).data('data')['sole'] == '1' && $('div[path][data-appid="' + $(this).data('data')['id'] + '"]').length) {
            soleApp.push($(this).data('data')['name'])
        }
    });
    if (soleApp.length) {
        top.Alert('复制的内容中 ' + soleApp + ' 不能在一个页面中放置两个，因此不能粘贴！')
    };
    return soleApp.length ? false: data
};
function setNextWidth(ek) {
    var ev = ek.next().length ? ek.next() : ek.siblings().first(),
    nw = getSpanNum(ev);
    if (nw > 1) {
        ev.removeClass().addClass('span' + (nw - 1))
    } else {
        setNextWidth(ev)
    }
};
function copyEl(el) {
    var elClone = el.clone(true),
    styleData = '';
    elClone.removeClass('selectedTools currentTools');
    if ((el.attr('path') == 'app' && el.data('content') == 'json') || el.attr('static')) {
        var id = el.attr('id');
        if (el.attr('static')) {
            styleData = $('#' + id + '_static', pageLayout).clone(true)
        } else {
            if ($('#' + id + '_style', pageLayout).length) {
                styleData = $('#' + id + '_style', pageLayout).clone(true)
            }
        }
    };
    top.$HASH['pasteData'] = {
        path: elClone.attr('path'),
        data: elClone,
        style: styleData
    }
};
function pasteEl(el) {
    var path = el.attr('path'),
    target = getPasteData(),
    tPath = top.$HASH['pasteData']['path'];
    if (!target) return;
    var tid = target.attr('id');
    if (target.attr('static')) {
        if (currentToolsId == tid) {
            selectedBody()
        };
        if (target.attr('static') != 'root') {
            if ($('#' + target.attr('static'), pageLayout).length) {
                target.appendTo($('#' + target.attr('static'), pageLayout))
            } else {
                target.appendTo(pageLayout)
            }
        } else {
            if (tid == 'header') {
                if ($('#main', pageLayout).length) {
                    target.insertBefore($('#main', pageLayout))
                } else {
                    target.appendTo(pageLayout)
                }
            } else if (tid == 'main') {
                if ($('#footer', pageLayout).length) {
                    target.insertBefore($('#footer', pageLayout))
                } else {
                    target.appendTo(pageLayout)
                }
            } else if (tid == 'footer') {
                if ($('#main', pageLayout).length) {
                    target.insertAfter($('#main', pageLayout))
                } else {
                    target.appendTo(pageLayout)
                }
            } else if (tid == 'wrapper') {
                target.appendTo(pageLayout)
            }
        }
    } else {
        if (path == 'column') {
            if (tPath == 'column') {
                var span = el.parent().parent(),
                siblings = span.siblings();
                if (siblings.length == maxColumn - 1) {
                    top.Alert('当前行最多可以放' + maxColumn + '列，因此不能粘贴');
                    return
                } else {
                    var newWidth = 6;
                    if (getSpanNum(span) == 12) {
                        span.removeClass().addClass('span6')
                    } else {
                        setNextWidth(span);
                        newWidth = 1
                    };
                    $('<div class="span' + newWidth + '"><div class="boxBlock"></div></div>').insertAfter(span).find('>div').append(target)
                };
                clearLayoutSet(span.parents('div.row:first'));
                if (currentToolsId == el.attr('id')) {
                    setLayout()
                }
            } else {
                target.appendTo(el);
                target.siblings('div[role="dragEmptyEl"]').remove()
            }
        } else {
            if (tPath == 'column') {
                if (path == 'row') {
                    var span = el.find('>div >div:first'),
                    siblings = span.siblings();
                    if (siblings.length == maxColumn - 1) {
                        top.Alert('当前行最多可以放' + maxColumn - 1 + '列，因此不能粘贴');
                        return
                    } else {
                        if (!siblings.length) {
                            span.removeClass().addClass('span11')
                        } else {
                            setNextWidth(span)
                        };
                        $('<div class="span1"><div class="boxBlock"></div></div>').insertBefore(span).find('>div').append(target);
                        clearLayoutSet(el)
                    }
                } else {
                    getEmptyRow().insertAfter(el).find('>div >div >div').append(target)
                }
            } else {
                target.insertAfter(el)
            }
        }
    };
    if (top.$HASH['pasteData']['style']) {
        var styleEl = $.extend(true, {},
        top.$HASH['pasteData']['style'].clone(true));
        if (target.attr('static')) {
            $('#' + tid + '_static', pageLayout).replaceWith(styleEl)
        } else {
            var oldId = top.$HASH['pasteData']['data'].attr('id'),
            newId = target.attr('id');
            replaceStyleId(styleEl, oldId, newId);
            styleEl.insertBefore(target)
        }
    };
    change()
};
function deleteEl(el) {
    if (currentToolsId == el.attr('id')) {
        removeSelectedTools();
        setPath()
    } else {
        hideSelectedTools()
    };
    if (el.attr('path') == 'column') {
        var row = el.parents('div.row:first');
        if (!el.parent().parent().siblings().length) {
            if (!row.siblings('div[path]').length) {
                $(getEmptyEl()).insertAfter(row)
            };
            row.remove()
        } else {
            var span = el.parent().parent(),
            sib = span.next().length ? span.next() : span.prev(),
            num = getSpanNum(span),
            bnum = getSpanNum(sib);
            sib.removeClass().addClass('span' + (bnum + num));
            span.remove();
            clearLayoutSet(row)
        }
    } else {
        if (!el.siblings('div[path]').length) {
            $(getEmptyEl()).insertAfter(el)
        };
        if (el.attr('path') == 'app' && el.data('content') == 'json') {
            var id = el.attr('id');
            if ($('#' + id + '_style', pageLayout).length) {
                $('#' + id + '_style', pageLayout).remove()
            }
        };
        el.remove()
    };
    change()
};
top.appsettingReady = function(form) {
    top.$HASH['appSettingForm'] = form;
    top.$('#appSettingIframe').css('opacity', 1).prev().remove()
};
function appSetting(app) {
    var data = app.data('data'),
    options = $.toJSON(data['options']),
    appSettingIframe = '<iframe id="appSettingIframe" src="' + top.appSettingURL + '" width="100%" height="100%" frameborder="0" scrolling="auto" style="opacity:0"></iframe>',
    el = $('<div style="height:100%;">' + getContentLoading() + '</div>');
    top.ConfirmDialog(data.name + ' - 设置', el, {
        width: 1000,
        height: 700,
        scroll: false,
        onBeforeClose: function(fn, type) {
            if (type == 'confirm' && top.$HASH['appSettingCheck']) {
                top.$HASH['appSettingCheck'](fn)
            } else {
                fn()
            }
        },
        onClose: function() {
            delete top.$HASH['appSettingForm'];
            delete top.$HASH['appSettingCheck']
        },
        onConfirm: function() {
            if (!top.$HASH['appSettingForm']) return;
            data['options'] = getFormValue(top.$HASH['appSettingForm']);
            app.data('data', data).attr('data-data', $.toJSON(data));
            reloadApp(app, change)
        }
    });
    rpcJSON('setAppSettings', {
        data: data
    },
    function(backData) {
        el.append(appSettingIframe)
    })
};
function appManage(app) {
    var appManageURL = app.data('manageurl'),
    appSettingIframe = '<iframe id="appManageIframe" src="' + appManageURL + '" width="100%" height="100%" frameborder="0" scrolling="auto"></iframe>';
    top.ConfirmDialog(app.data('data')['name'] + ' - 管理', appSettingIframe, {
        scroll: false,
        width: 1000,
        height: 700,
        buttons: '',
        onClose: function() {
            reloadApp(app)
        }
    })
};
var elToolsPanel,
delayHideElTools,
selectedTools,
currentTools;
function setElTools() {
    elToolsPanel = $('<div id="elToolsPanel" class="dressTips"></div>').hide().appendTo(pageBody).on({
        mouseover: function(e) {
            if (appDraggableIng) return;
            clearTimeout(delayHideElTools)
        },
        mouseout: function() {
            if (appDraggableIng) return;
            delayHideElTools = setTimeout(hideElTools, 100)
        }
    });
    $HASH['iframeObj'].setDraggable();
    pageBody.delegate('#elToolsPanel li[role]:not(.disabled),#elToolsPanel span[role]:not(.disabled)', click, 
    function(e) {
        var $this = $(this),
        path = currentTools.attr('path'),
        role = $this.attr('role');
        if ($.inArray(role, ['refresh', 'delete', 'copy', 'cut', 'paste', 'merge', 'split']) < 0) {
            selectElTools(currentTools)
        };
        switch (role) {
        case 'up':
            currentTools.insertBefore(currentTools.prev());
            $('li[role="down"].disabled', elToolsPanel).removeClass('disabled');
            if (!currentTools.prev().length) {
                $this.addClass('disabled')
            };
            change();
            resetToolsPosition(currentTools);
            break;
        case 'down':
            currentTools.insertAfter(currentTools.next());
            $('li[role="up"].disabled', elToolsPanel).removeClass('disabled');
            if (!currentTools.next().length) {
                $this.addClass('disabled')
            };
            change();
            resetToolsPosition(currentTools);
            break;
        case 'left':
            currentTools.parent().parent().insertBefore(currentTools.parent().parent().prev());
            $('li[role="right"].disabled', elToolsPanel).removeClass('disabled');
            if (!currentTools.parent().parent().prev().length) {
                $this.addClass('disabled')
            };
            clearLayoutSet(currentTools.parents('div.row:first'));
            setLayout();
            change();
            resetToolsPosition(currentTools);
            break;
        case 'right':
            currentTools.parent().parent().insertAfter(currentTools.parent().parent().next());
            $('li[role="left"].disabled', elToolsPanel).removeClass('disabled');
            if (!currentTools.parent().parent().next().length) {
                $this.addClass('disabled')
            };
            clearLayoutSet(currentTools.parents('div.row:first'));
            setLayout();
            change();
            resetToolsPosition(currentTools);
            break;
        case 'copy':
            copyEl(currentTools);
            $('#elToolsPanel li[role="paste"]', pageBody).removeClass('disabled');
            Tips('success', '复制成功');
            break;
        case 'cut':
            copyEl(currentTools);
            deleteEl(currentTools);
            break;
        case 'paste':
            pasteEl(currentTools);
            break;
        case 'delete':
            deleteEl(currentTools);
            break;
        case 'set':
            var fn = staticFunctions[currentTools.data('data')['id']];
            if (fn) {
                setFunction(fn, currentTools)
            } else {
                appSetting(currentTools)
            };
            break;
        case 'manage':
            appManage(currentTools);
            break;
        case 'refresh':
            reloadApp(currentTools);
            break;
        case 'merge':
            var span = $('>div >div:first', currentTools),
            elementContainer = span.find('>div >div');
            span.siblings().find('>div >div >div[role="dragEl"]').appendTo(elementContainer);
            if ($('>div', elementContainer).length > 1) {
                $('>div[role="dragEmptyEl"]', elementContainer).remove()
            };
            span.removeClass().addClass('span12').siblings().remove();
            $('#elToolsPanel li[role="merge"]', pageBody).addClass('disabled');
            clearLayoutSet(currentTools);
            change();
            break;
        case 'split':
            var span = currentTools.parent().parent(),
            num = getSpanNum(span),
            sl = maxColumn - span.siblings().length,
            es = $('<div><table width="100%" border="0" cellpadding="5" cellspacing="0">' + '<tbody>' + '<tr>' + '<td width="100">拆分几列：</td>' + '<td><select name="columns"></select>' + '</td>' + '</tr>' + '</tbody>' + '</table></div>');
            if (sl > num) {
                sl = num
            };
            for (i = 2; i <= sl; i++) {
                $('<option>' + i + '</option>').appendTo($('select', es))
            };
            top.ConfirmDialog('拆分列', es, {
                width: 450,
                height: 300,
                onClose: $.noop,
                onConfirm: function() {
                    var columns = $('select[name="columns"]', es).val(),
                    cw = Math.floor(num / columns),
                    html = '';
                    for (j = 1; j < columns; j++) {
                        html += '<div class="span' + cw + '"><div class="boxBlock"><div class="elementContainer" role="dropEl" path="column">' + getEmptyEl() + '</div></div></div>'
                    };
                    var et = $(html);
                    span.removeClass().addClass('span' + (cw + (num % columns)));
                    et.insertAfter(span);
                    clearLayoutSet(span.parents('div.row:first'));
                    if (currentToolsId == currentTools.attr('id')) {
                        setLayout()
                    };
                    change()
                }
            });
            break
        };
        e.stopPropagation();
        e.preventDefault()
    }).delegate('#elToolsPanel', click, 
    function(e) {
        e.stopPropagation();
        e.preventDefault()
    });
    pageBody.delegate('div[path],header[path],footer[path]', {
        mouseover: function(e) {
            if (appDraggableIng || editorMode) return;
            clearTimeout(delayHideElTools);
            showElTools($(this));
            e.stopPropagation()
        },
        mouseout: function() {
            if (appDraggableIng || editorMode) return;
            clearTimeout(delayHideElTools);
            delayHideElTools = setTimeout(hideElTools, 100)
        }
    }).delegate('div[path],header[path],footer[path]', click, 
    function(e) {
        if (editorMode) {
            if ($(this).hasClass('selectedTools')) {
                e.stopPropagation();
                e.preventDefault()
            };
            return
        };
        if (!$(this).hasClass('selectedTools')) {
            selectElTools($(this))
        } else {
            selectedBody()
        };
        e.stopPropagation();
        e.preventDefault()
    }).on(click, 
    function() {
        if (editorMode) {
            clearEditor()
        } else {
            selectedBody()
        }
    })
};
function getElTools(el) {
    var name,
    path = el.attr('path'),
    html = '<div class="dressTitle t_c3 ' + ($.inArray(path, dragElArr) >= 0 ? 'draggable': '') + '">';
    if (path == 'app') {
        var data = el.data('data');
        name = data.name;
        if (el.data('content') == 'json') {
            html += '<span class="icon-spinner cursor" title="刷新" role="refresh" data-tips="3_t"></span>'
        }
    } else {
        name = pathName[path]
    };
    if ($.inArray(path, dragElArr) >= 0) {
        html += '<i class="icon-td h4"></i>&nbsp;'
    };
    html += '<span role="name">' + name + '</span>' + '</div>' + '<div class="dressPad clearfix">' + '<div class="dressBtnBar">' + '<ul class="dressBtnUl">';
    if (path == 'column') {
        html += '<li role="left" ' + (el.parent().parent().prev().length ? '': 'class="disabled"') + ' title="左移" data-tips="3_t"><span class="icon-arrow-left"></span></li>' + '<li role="right" ' + (el.parent().parent().next().length ? '': 'class="disabled"') + ' title="右移" data-tips="3_t"><span class="icon-arrow-right"></span></li>'
    } else {
        html += '<li role="up" ' + (el.prev().length ? '': 'class="disabled"') + ' title="上移" data-tips="3_t"><span class="icon-arrow-up"></span></li>' + '<li role="down" ' + (el.next().length ? '': 'class="disabled"') + ' title="下移" data-tips="3_t"><span class="icon-arrow-down"></span></li>'
    };
    html += '</ul>';
    if (path == 'app') {
        html += '<ul class="dressBtnUl">' + '<li role="set" ' + ((el.data('data')['options'] || staticFunctions[el.data('data')['id']]) ? '': 'class="disabled"') + ' title="设置" data-tips="3_t"><span class="icon-cog"></span></li>' + '<li role="manage" ' + (!el.data('manageurl') ? 'class="disabled"': '') + ' title="管理" data-tips="3_t"><span class="icon-wrench"></span></li>' + '</ul>'
    } else if (path == 'column') {
        html += '<ul class="dressBtnUl">' + '<li role="split" ' + ((getSpanNum(el.parent()) == 1 || el.parent().siblings().length >= maxColumn - 1) ? 'class="disabled"': '') + ' title="拆分列" data-tips="3_t"><span class="icon-cf"></span></li>' + '</ul>'
    } else if (path == 'row') {
        html += '<ul class="dressBtnUl">' + '<li role="merge" ' + (el.find('>div >div >div').length == 1 ? 'class="disabled"': '') + ' title="合并列" data-tips="3_t"><span class="icon-hb"></span></li>' + '</ul>'
    };
    html += '<ul class="dressBtnUl">' + ' <li role="copy" title="复制" data-tips="3_t"><span class="icon-copy"></span></li>' + '<li role="paste" ' + (!top.$HASH['pasteData'] ? 'class="disabled"': '') + ' title="粘贴" data-tips="3_t"><span class="icon-paste"></span></li>' + '<li role="cut" ' + ((el.data('del') == false) ? 'class="disabled"': '') + ' title="剪切" data-tips="3_t"><span class="icon-scissors"></span></li>' + '<li role="delete" ' + ((el.data('del') == false) ? 'class="disabled"': '') + ' title="删除" data-tips="3_t"><span class="icon-remove"></span></li>' + '</ul>' + '</div>' + '</div>';
    elToolsPanel.html(html);
    currentTools = el;
    resetToolsPosition(el);
    elToolsPanel.show();
    if ($.inArray(path, dragElArr) >= 0) {
        $HASH['iframeObj'].enableDraggable()
    } else {
        $HASH['iframeObj'].disableDraggable()
    }
};
function resetToolsPosition(el, flag) {
    el = el || selectedTools;
    if (!el) return;
    var top = el.offset().top - elToolsPanelHeight,
    left = el.offset().left;
    if (top < $HASH['iframeScrollTop']) {
        top = el.offset().top + el.outerHeight();
        if (top + elToolsPanelHeight > $HASH['iframeScrollTop'] + frameContainer.height()) {
            top = $HASH['iframeScrollTop']
        }
    }
    if (left + elToolsPanel.outerWidth() > frameContainer.width()) {
        left = frameContainer.width() - elToolsPanel.outerWidth()
    };
    elToolsPanel.css({
        left: left,
        top: top
    })
};
function showElTools(el) {
    hideElTools();
    if (!selectedTools) {
        getElTools(el)
    };
    el.addClass('currentTools')
};
function hideElTools() {
    if (!selectedTools) {
        elToolsPanel.hide()
    };
    $('.currentTools:not(.selectedTools)', pageBody).removeClass('currentTools');
    clearTimeout(delayHideElTools)
};
function getElId(el) {
    var id = el.attr('id');
    if (!id) {
        id = 'el_' + getNewId();
        el.attr('id', id)
    };
    return id
};
function selectElTools(el, enforce, noTools) {
    if ((el.hasClass('selectedTools') && !enforce) || appDraggableIng) {
        return
    };
    if (!noTools) {
        removeSelectedTools(1)
    };
    selectedTools = el;
    el.addClass('selectedTools currentTools');
    getElTools(el);
    var pData = {
        id: getElId(el),
        path: el.attr('path'),
        active: true
    },
    pathData = [];
    if (el.attr('path') == 'app') {
        pData.name = el.data('data').name
    };
    var pathData = [pData];
    el.parents('div[path],header[path],footer[path]').each(function(i, item) {
        pathData.unshift({
            id: getElId($(this)),
            path: $(this).attr('path')
        })
    });
    setPath(pathData, noTools)
};
function removeSelectedTools(num) {
    if (!selectedTools) return;
    $('div.selectedTools,header.selectedTools,footer.selectedTools', pageBody).removeClass('selectedTools currentTools');
    if (num != 1) {
        selectedTools = null;
        elToolsPanel.hide()
    }
};
function hideSelectedTools() {
    elToolsPanel.hide();
    if (selectedTools) {
        selectedTools.removeClass('currentTools')
    }
};
function selectedBody(noTools) {
    removeSelectedTools();
    setPath('', noTools)
};
var pathPanel = $('#pathPanel');
function setPath(data, noTools) {
    if (!data) {
        data = [{
            name: '网页',
            id: 'body',
            active: true
        }]
    } else {
        data = $.merge([{
            name: '网页',
            id: 'body'
        }], data)
    };
    var sid = '',
    html = '';
    $.each(data, 
    function(i, item) {
        if (item.active) {
            sid = item.id
        };
        html += '<li data-id="' + item.id + '" ' + (item.active ? 'class="active"': '') + '>' + (item.name ? item.name: pathName[item.path]) + '</li>'
    });
    pathPanel.html(html);
    if (!noTools) {
        setTools(sid)
    } else {
        if (currentToolsId == 'body') {
            setPageInfo();
            getElStyle('body');
            return
        } else if (selectedTools.attr('path') == 'app') {
            $('div[role="styleContainer"]:not(:empty)', toolsMain).each(function() {
                getElStyle(selectedTools, $(this).data('selector'))
            });
            if ($('div[role="styleListContainer"]:not(:empty)', toolsMain).length) {
                var templateId = selectedTools.data('data')['styles']['template'];
                $('div[role="styleListContainer"] li[data-id="' + templateId + '"]', toolsMain).toActive()
            };
            if ($('div[role="appColumnContainer"]:not(:empty)', toolsMain).length) {
                setAppColumn()
            };
            resetMoreStyle()
        } else if (selectedTools.attr('path') == 'column') {
            getElStyle(selectedTools, '> .elementContainer')
        } else {
            getElStyle(selectedTools, '')
        };
        resetProperties();
        resetAddEvents()
    }
};
pathPanel.delegate('li:not(.active)', {
    mouseover: function(e) {
        var id = $(this).data('id');
        if (id == 'body') return;
        $('#' + id, pageBody).trigger('mouseover');
        e.stopPropagation()
    },
    mouseout: function(e) {
        var id = $(this).data('id');
        if (id == 'body') return;
        $('#' + id, pageBody).trigger('mouseout');
        e.stopPropagation()
    }
}).delegate('li:not(.active)', click, 
function(e) {
    if (editorMode) clearEditor();
    var id = $(this).data('id');
    if (id == 'body') {
        selectedBody()
    } else {
        $('#' + id, pageBody).trigger(click)
    };
    e.stopPropagation();
    e.preventDefault()
});
var appDraggableIng = false,
appDraggableCanDrop = false,
appDraggablePlaceholder;
function appDraggableStart(event, ui) {
    appDraggableIng = true;
    currentTools.addClass('elDraggable');
    $('div[role="dragEl"],div[role="dragEmptyEl"]', currentTools).attr('dragDisabled', 1);
    appDraggablePlaceholder = $('<div class="sortablePlaceholder"><div><b></b><i></i></div></div>').appendTo(pageBody).hide()
};
function appDraggableDrag(event, ui) {
    appDraggableCanDrop = false;
    $('div[role="dragEl"]:not([dragDisabled]),div[role="dragEmptyEl"]:not([dragDisabled])', pageBody).each(function() {
        var kl = event.pageX,
        kt = event.pageY,
        direction = '',
        $this = $(this);
        if (kl > $this.offset().left && kl < $this.offset().left + $this.outerWidth()) {
            if (kt > $this.offset().top && kt < $this.offset().top + $this.outerHeight() / 2) {
                direction = 'up'
            } else if (kt < $this.offset().top + $this.outerHeight() && kt > $this.offset().top + $this.outerHeight() / 2) {
                direction = 'down'
            };
            drop = true
        };
        if (direction == 'up') {
            appDraggablePlaceholder.insertBefore($this)
        } else if (direction == 'down') {
            appDraggablePlaceholder.insertAfter($this)
        };
        if (direction) {
            appDraggablePlaceholder.show();
            appDraggableCanDrop = true
        }
    });
    if (appDraggableCanDrop) {
        appDraggablePlaceholder.show()
    } else {
        appDraggablePlaceholder.hide()
    }
};
function appDraggableStop(event, ui) {
    appDraggableIng = false;
    if (appDraggableCanDrop) {
        var insertEl = currentTools,
        check = true;
        if (currentTools.attr('path') == 'column') {
            var span = currentTools.parent(),
            num = getSpanNum(span);
            if (num == 12) {
                insertEl = span.parents('div.row:first')
            } else {
                check = false;
                var sib = span.next().length ? span.next() : span.prev(),
                bnum = getSpanNum(sib);
                sib.removeClass().addClass('span' + (bnum + num));
                insertEl = getEmptyRow();
                insertEl.find('>div >div >div').append(currentTools);
                span.remove()
            }
        };
        if (!insertEl.siblings('div[path]').length && check) {
            $(getEmptyEl()).insertAfter(insertEl)
        };
        insertEl.insertAfter(appDraggablePlaceholder).siblings('div[role="dragEmptyEl"]').remove();
        if (currentTools.attr('path') == 'app' && currentTools.data('content') == 'json' && $('#' + currentTools.attr('id') + '_style', pageLayout).length) {
            $('#' + currentTools.attr('id') + '_style', pageLayout).insertBefore(insertEl)
        }
    };
    currentTools.removeClass('elDraggable');
    appDraggablePlaceholder.remove();
    $('div[dragDisabled]', pageLayout).removeAttr('dragDisabled');
    if (appDraggableCanDrop) {
        selectElTools(currentTools, 1);
        change()
    }
};
function changePageTemplate(id) {
    top.Confirm('<h3 class="ct_5">更换模板会替换本页内容和所有设置，且不能撤销。<br>确定要继续操作吗？</h3>', 
    function() {
        rpcJSON('changePageTamplate', {
            pageId: pageId,
            templateId: id
        },
        function() {
            top.updateHistory('historyPageTamplates', id);
            window.location.reload()
        })
    })
};
function resetPageSkin(skin) {
    pageBody.find('#skinLink').remove();
    pageBody.prepend('<link data-href="' + skin + '" href="' + skin + '" rel="stylesheet" type="text/css" id="skinLink">')
};
function changePageSkin(id, skin) {
    if (pageBody.find('#skinLink').data('href') == skin) return;
    resetPageSkin(skin);
    top.updateHistory('historyPageSkins', id);
    pageData.skinId = id;
    change('pageData')
};
function resetProperties() {
    var path = selectedTools.attr('path');
    if (path == 'row' || path == 'column') {
        setLayout()
    } else if (path == 'app') {
        switch (selectedTools.data('data')['id']) {
        case 'image':
            setImageInfo();
            break
        }
    }
};
function getProperties() {
    var path = selectedTools.attr('path'),
    container = $('div[role="properties"]', toolsMain),
    name = $('#pathPanel li.active').text(),
    id = selectedTools.attr('id');
    $('<div class="ct_2 h6">名称：' + name + '</div><div class="ct_2 pt5 h6">ID：' + id + '</div>').appendTo(container);
    if (path == 'app') {
        if (selectedTools.data('data')['id'] == 'image') {
            getImageInfo()
        }
    } else if (path == 'row' || path == 'column') {
        $('<div role="setLayoutContainer" class="ct_2"></div>').appendTo(container).html($('#setLayoutTemp').html()).delegate('div.layoutSetIconBox:not(.active,[role=customize])', click, 
        function() {
            var role = $(this).attr('role'),
            screenType = $(this).parents('div.layoutSetList:first').attr('role');
            setLayout(screenType, role, 1);
            setRulers('', screenType)
        });
        setLayout();
        resizeToolsScroll()
    }
};
function getImageInfo() {
    var path = selectedTools.attr('path'),
    container = $('div[role="properties"]', toolsMain),
    id = selectedTools.attr('id');
    $('<div role="setImageContainer" class="ct_2"></div>').appendTo(container).html($('#imageInfoTemp').html()).delegate('input[type="text"]', 'blur', 
    function() {
        resetImage($(this))
    }).delegate('input[type="radio"]', click, 
    function() {
        resetImage($(this))
    }).delegate('a[role="selectPage"]', click, 
    function() {
        var input = $(this).prev();
        top.selectPageUrl(input, 
        function(backData) {
            input.trigger('blur')
        })
    });
    setImageInfo();
    resizeToolsScroll();
    var resetImage = function(input) {
        var img = $('img', selectedTools),
        data = getImageData(img),
        imgData = getFormValue($('div[role="setImageContainer"] form', container)),
        targetContainer = $('div[role="targetContainer"]', container),
        name = input.attr('name');
        if (data[name] == imgData[name]) return;
        img.attr('title', imgData.title);
        if (imgData.responsive == '1') {
            if (!img.hasClass('responsiveImage')) {
                img.addClass('responsiveImage');
                $HASH['iframeObj'].$('#' + currentToolsId + ' img').removeData('src').responsiveImage(1)
            }
        } else {
            if (img.hasClass('responsiveImage')) {
                img.removeClass('responsiveImage').attr('src', img.data('src')).css('opacity', 1)
            }
        };
        if (imgData.href && imgData.href != 'http://') {
            if (img.parent('a').length) {
                img.parent('a').attr({
                    'href': imgData.href,
                    target: imgData.target
                })
            } else {
                var a = $('<a href="' + imgData.href + '" target="' + imgData.target + '"></a>');
                img.parent().append(a);
                a.append(img)
            };
            targetContainer.show()
        } else {
            if (img.parent('a').length) {
                img.parent('a').replaceWith(img)
            };
            targetContainer.hide()
        };
        change()
    }
};
function setImageInfo(flag) {
    var form = $('div[role="properties"] div[role="setImageContainer"] form', toolsMain),
    targetContainer = $('div[role="targetContainer"]', form),
    imgData = getImageData();
    for (name in imgData) {
        setInputValue(name, imgData[name], form)
    };
    if (imgData.href && imgData.href != 'http://') {
        targetContainer.show()
    } else {
        targetContainer.hide()
    }
};
function getImageData(img) {
    var img = img || $('img', selectedTools);
    if (!img.length) return {};
    return {
        title: img.attr('title') || '',
        target: img.parent('a').length ? img.parent('a').attr('target') ? img.parent('a').attr('target') : '': '',
        href: img.parent('a').length ? img.parent('a').attr('href') : '',
        responsive: img.hasClass('responsiveImage') ? '1': '0'
    }
};
function getAppLayout() {
    var container = $('div[role="appLayoutContainer"]', toolsMain),
    name = $('#pathPanel li.active').text(),
    id = selectedTools.attr('id');
    $('<div class="h6 ct_1">设置' + name + '的排版</div>').appendTo(container);
    if (selectedTools.data('data')['stylesList']) {
        $('<dl class="setPanel">' + '<dt><i class="trigon ct_3 small left"></i>设置版式</dt>' + '<dd>' + '<div class="appSetStyle setPanelMain">' + '<div role="styleListContainer"></div>' + '</div>' + '</dd>' + '</dl>').appendTo(container).delegate('dt', click, 
        function() {
            $(this).find('>i').toggleClass('top left');
            $(this).next().find('>div').toggleClass('active');
            resizeToolsScroll();
            var styleListContainer = $(this).next().find('div[role="styleListContainer"]');
            if (!styleListContainer.children().length) {
                styleListContainer.html(getContentLoading());
                setAppTemplate(id)
            }
        })
    };
    if (selectedTools.find('div.appRow').length) {
        $('<dl class="setPanel">' + '<dt><i class="trigon ct_3 small left"></i>设置列数</dt>' + '<dd>' + '<div class="setPanelMain">' + '<div role="appColumnContainer" class="ct_2"></div>' + '</div>' + '</dd>' + '</dl>').appendTo(container).delegate('dt', click, 
        function() {
            $(this).find('>i').toggleClass('top left');
            $(this).next().find('>div').toggleClass('active');
            resizeToolsScroll();
            var appColumnContainer = $(this).next().find('div[role="appColumnContainer"]');
            if (!appColumnContainer.children().length) {
                appColumnContainer.html($('#appColumnTemp').html()).delegate('div.layoutSetIconBox', click, 
                function() {
                    setAppColumn($(this).parents('div.layoutSetList:first').attr('role'), $(this).attr('role'), 1);
                    setRulers('', $(this).parents('div.layoutSetList:first').attr('role'))
                });
                setAppColumn();
                resizeToolsScroll()
            }
        })
    } else {
        $('dt:first', container).trigger(click)
    }
};
function setAppTemplate(id) {
    var styleListContainer = $('div[role="styleListContainer"]', toolsMain),
    data = $('#' + id, pageLayout).data('data');
    rpcJSON('getAppStyles', {
        appId: data.id,
        type: data.type
    },
    function(backData) {
        var html = '<div class="appSetStyle clearfix"><ul>';
        $.each(backData.template, 
        function(i, item) {
            html += '<li data-id="' + item.id + '" ';
            if (item.id == data.styles.template) {
                html += 'class="active"'
            };
            html += '><div><img src="' + item.icon + '"></div></li>'
        });
        html += '</ul></div>';
        styleListContainer.html(html).delegate('li', click, 
        function() {
            if ($(this).hasClass('active')) return;
            $(this).toActive();
            var el = $('#' + id, pageLayout),
            data = el.data('data');
            data.styles.template = $(this).data('id');
            el.removeData('data').attr('data-data', $.toJSON(data));
            reloadApp(el, 
            function() {
                change();
                resetMoreStyle()
            })
        });
        resizeToolsScroll()
    })
};
function setAppColumn(screenType, role, setRow) {
    var appColumnContainer = $('div[role="appColumnContainer"]', toolsMain),
    appRow = $('div.appRow', selectedTools),
    data = selectedTools.data('data'),
    appRowClass = '',
    appRowData = {
        'min1200': '',
        '961_1199': '',
        '768_960': '',
        '480_767': '',
        'max479': ''
    };
    $.each(appRow.attr('class').split(' '), 
    function(i, item) {
        for (key in appRowData) {
            if (item.indexOf(key) >= 0) {
                appRowData[key] = item.replace('list_' + key + '_', '')
            }
        }
    });
    if (screenType && role) {
        appRowData[screenType] = role
    };
    for (key in appRowData) {
        $('div.layoutSetList[role="' + key + '"] div.layoutSetIconBox', appColumnContainer).removeClass('active');
        $('div.layoutSetList[role="' + key + '"] div.layoutSetIconBox[role="' + appRowData[key] + '"]', appColumnContainer).addClass('active');
        appRowClass += ' list_' + key + '_' + appRowData[key]
    };
    if (setRow) {
        data.styles.appRowClass = appRowClass;
        appRow.removeClass().addClass('appRow' + appRowClass);
        selectedTools.removeData('data').attr('data-data', $.toJSON(data));
        change()
    }
};
function clearLayoutSet(row) {
    if (row.attr('data-layout')) {
        var layoutData = row.data('layout');
        for (key in layoutData) {
            if (key != 'basic') {
                row.removeAttr('column_' + key)
            }
        };
        row.removeData('layout').removeAttr('data-layout');
        if (row.attr('id') == currentToolsId) {
            setLayout()
        }
    }
};
function setLayout(screenType, role, setRow, noCuz) {
    var list = ['12', '6_6', '3_9', '9_3', '4_4_4', '3_6_3', '3_3_3_3', '2_3_5_2', '2_2_2_2_2_2'],
    container = $('div[role="setLayoutContainer"]', toolsMain),
    row = selectedTools.attr('path') == 'row' ? selectedTools: selectedTools.parents('div[path=row]:first'),
    layoutData = row.data('layout'),
    basicColumn = '',
    columns = 1,
    className = ['12', '12_12', '6_6', '4_4_4', '3_3_3_3', '', '2_2_2_2_2_2'],
    cList = [],
    customize = false,
    setPanel = function() {
        basicColumn = layoutData['basic'];
        if ($.inArray(basicColumn, list) < 0) {
            customize = true
        };
        columns = basicColumn.split('_').length;
        switch (columns) {
        case 2:
            cList = [2];
            break;
        case 3:
            cList = [3];
            break;
        case 4:
            cList = [2, 4];
            break;
        case 6:
            cList = [2, 3, 6];
            break
        };
        cList.unshift('1');
        for (key in layoutData) {
            var listContainer = $('div.layoutSetList[role="' + key + '"] ul', container);
            if (key == 'basic') {
                $('div.layoutSetIconBox', listContainer).removeClass('active');
                $('div.layoutSetIconBox[role="' + (customize ? 'customize': layoutData['basic']) + '"]', listContainer).addClass('active')
            } else {
                var listHtml = '';
                $.each(cList, 
                function(i, item) {
                    listHtml += getLi(item, className[item])
                });
                if (basicColumn != '12' && $.inArray(basicColumn, className) < 0) {
                    listHtml += getLi('no', customize ? 'customize': basicColumn)
                };
                listContainer.html(listHtml).find('div.layoutSetIconBox[role="' + layoutData[key] + '"]').addClass('active')
            }
        };
        if ((screenType == 'basic' && !noCuz) || !screenType) {
            setCustomize(basicColumn)
        }
    },
    getLi = function(r, c) {
        return '<li>' + '<div class="layoutSetListPad">' + '<div class="layoutSetIconBox" role="' + r + '">' + '<i class="layoutSetIcon_' + c + '"></i>' + '</div>' + '</div>' + '</li>'
    };
    if (!layoutData) {
        var cls = '';
        $('>div >div', row).each(function(i) {
            if (i > 0) {
                cls += '_'
            };
            cls += $(this).attr('class').replace('span', '')
        });
        layoutData = {
            'basic': cls,
            '768_960': cls == 12 ? '1': $.inArray(cls, className) >= 0 ? $.inArray(cls, className) : 'no',
            '480_767': '1',
            'max479': '1'
        }
    };
    if (screenType) {
        if (screenType == 'basic') {
            layoutData = {
                'basic': role,
                '768_960': role == 12 ? '1': $.inArray(role, className) >= 0 ? $.inArray(role, className) : 'no',
                '480_767': '1',
                'max479': '1'
            };
            setPanel()
        } else {
            layoutData[screenType] = role;
            $('div.layoutSetList[role="' + screenType + '"] div.layoutSetIconBox', container).removeClass('active');
            $('div.layoutSetList[role="' + screenType + '"] div.layoutSetIconBox[role="' + role + '"]', container).addClass('active')
        }
    } else {
        setPanel()
    };
    if (setRow) {
        row.removeData('layout').attr('data-layout', $.toJSON(layoutData));
        if (screenType == 'basic') {
            var cloumns = basicColumn.split('_'),
            spans = $('>div.rowPatch >div[class*=span]', row);
            $.each(cloumns, 
            function(i, item) {
                var cloumn = $('>div >div:eq(' + i + ')', row);
                if (cloumn.length) {
                    cloumn.removeClass().addClass('span' + item)
                }
            });
            if (spans.length > cloumns.length) {
                var selectRow = false;
                for (i = cloumns.length; i < spans.length; i++) {
                    if ($('div.elementContainer:first', spans[i]).hasClass('selectedTools')) {
                        selectRow = true
                    };
                    $(spans[i]).find('>div >div').children(':not([role="dragEmptyEl"])').appendTo($(spans[i]).prev().find('>div >div'));
                    $(spans[i]).remove()
                };
                if ($('>div.rowPatch >div:last >div >div', row).children().length > 1) {
                    $('>div.rowPatch >div:last >div >div >div[role="dragEmptyEl"]', row).remove()
                };
                if (selectRow) {
                    selectElTools(row)
                }
            } else if (spans.length < cloumns.length) {
                for (i = spans.length; i < cloumns.length; i++) {
                    $('<div class="span' + cloumns[i] + '" ><div class="boxBlock"><div class="elementContainer" path="column">' + getEmptyEl() + '</div></div></div>').appendTo($('>div.rowPatch', row))
                }
            }
        };
        for (key in layoutData) {
            if (key != 'basic') {
                row.attr('column_' + key, layoutData[key])
            }
        };
        change()
    }
};
function setCustomize(basicColumn) {
    var container = $('div[role="customizeContainer"]', toolsMain),
    html = '',
    direction,
    left,
    setWidth = function(column, direction) {
        var cSize = column.data('size'),
        sib = column.next(),
        sSize;
        if (direction == 'left') {
            cSize -= 1;
            sSize = sib.data('size') + 1
        } else {
            cSize += 1;
            sSize = sib.data('size') - 1
        };
        column.data('size', cSize).removeClass().addClass('col col-' + cSize);
        sib.data('size', sSize).removeClass().addClass('col col-' + sSize)
    };
    $.each(basicColumn.split('_'), 
    function(i, item) {
        html += '<div class="col col-' + item + '" data-size="' + item + '"><div class="columnsBox"><div class="handle"></div></div></div>'
    });
    container.html(html);
    if (basicColumn != '12') {
        container.find('div.handle').draggable({
            axis: 'x',
            grid: [18, 0],
            start: function(event, ui) {
                left = ui.offset.left;
                direction = null
            },
            drag: function(event, ui) {
                var column = ui.helper.parents('div.col:first'),
                cSize = column.data('size');
                if ((ui.offset.left - left > 0 && column.next().data('size') == 1) || (ui.offset.left - left < 0 && cSize == 1)) {
                    return false
                };
                if (ui.offset.left - left >= 18) {
                    direction = 'right'
                } else if (ui.offset.left - left <= -18) {
                    direction = 'left'
                };
                if (direction) {
                    setWidth(column, direction);
                    left = ui.offset.left;
                    direction = null
                }
            },
            stop: function() {
                var column = '';
                $('div.col', container).each(function(i, item) {
                    if (i > 0) {
                        column += '_'
                    };
                    column += $(this).data('size')
                });
                if (column != basicColumn) {
                    setLayout('basic', column, 1)
                }
            }
        })
    }
};
function setFunction(fn, el) {
    switch (fn) {
    case 'articleEditor':
        setEditor(el, 'article');
        break;
    case 'textEditor':
        setEditor(el, 'text');
        break;
    case 'setImage':
        setImage(el);
        break
    }
};
function setEditor(el, type) {
    $('>div.appMask', el).remove();
    var id = getElId(el.find('div[role="editor"]:first'));
    editorMode = id;
    $('#' + editorMode, pageLayout).data('oldHtml', $('#' + editorMode, pageLayout).html());
    $HASH['iframeObj'].setCKEDITOR(id, type);
    hideSelectedTools()
};
function clearEditor() {
    $HASH['iframeObj'].destroyCKEDITOR(editorMode);
    $('<div class="appMask"></div>').prependTo(selectedTools);
    elToolsPanel.show();
    selectedTools.addClass('currentTools');
    var oldHtml = $('#' + editorMode, pageLayout).data('oldHtml'),
    newHtml = $('#' + editorMode, pageLayout).html();
    $('#' + editorMode, pageLayout).removeData('oldHtml').removeAttr('id');
    if (oldHtml != newHtml) {
        change()
    };
    editorMode = false;
    resizeScroll()
};
function setImage(el) {
    var img = $('img', el);
    top.openFinder(function(backData) {
        img.attr('data-src', backData[0].src).attr('src', lazyLoadSrc);
        $HASH['iframeObj'].$('#' + currentToolsId + ' img').removeData('src').responsiveImage(1);
        change()
    })
};
var elEvents = {
    'click': '鼠标单击',
    'mouseenter': '鼠标移入',
    'mouseleave': '鼠标移出'
},
elEventsList = {
    'show': {
        'name': '显示元素',
        'el': true,
        'amniate': ['no', 'fadeIn', 'slideDown']
    },
    'hide': {
        'name': '隐藏元素',
        'el': true,
        'amniate': ['no', 'fadeOut', 'slideUp']
    },
    'toggle': {
        'name': '切换元素可见性',
        'el': true,
        'amniate': ['no', 'fadeToggle', 'slideToggle']
    },
    'selected': {
        'name': '选中元素',
        'el': true
    },
    'unSelected': {
        'name': '取消选中元素',
        'el': true
    },
    'move': {
        'name': '改变元素位置和大小',
        'el': true,
        'amniate': ['yes', 'no']
    },
    'zindex': {
        'name': '改变元素层级',
        'el': true
    },
    'content': {
        'name': '改变元素内容',
        'el': true
    },
    'scrollTo': {
        'name': '页面滚动到元素位置',
        'el': true,
        'amniate': ['yes', 'no']
    }
},
animations = {
    'no': '无动画',
    'yes': '有动画',
    'fadeIn': '透明淡入',
    'fadeOut': '透明淡出',
    'fadeToggle': '透明淡入淡出',
    'slideDown': '向下滑入',
    'slideUp': '向上滑出',
    'slideToggle': '上下滑入滑出'
};
function getEvents() {
    var container = $('div[role="eventsContainer"]', toolsMain),
    html = '',
    lhtml = '';
    for (key in elEventsList) {
        lhtml += '<li data-events="' + key + '" data-el="' + elEventsList[key]['el'] + '">' + elEventsList[key]['name'] + '</li>'
    };
    for (key in elEvents) {
        html += '<dl class="setPanel" role="' + key + '">' + '<dt>' + '<i class="trigon ct_3 small top"></i>' + elEvents[key] + '</dt>' + '<dd class="h6 ct_2">' + '<div class="pt10 addEvents"><a class="ct_6 h6" href="javascript:;" role="addEvents">+添加事件</a><div class="setSelectMain" role="addEventsList"><ul>' + lhtml + '</ul></div></div><ul role="eventsList" class="eventsList"></ul></dd></dl>'
    };
    container.html(html).delegate('a[role="addEvents"]', click, 
    function() {
        $(this).next().toggle();
        resizeToolsScroll()
    }).delegate('div[role="addEventsList"] li', click, 
    function() {
        $(this).parent().parent().hide();
        addEvents($(this).parents('dl:first').attr('role'), $(this).data('events'))
    }).delegate('dt', click, 
    function() {
        $(this).find('>i').toggleClass('top left');
        $(this).next().toggle();
        resizeToolsScroll()
    }).delegate('a[role]', click, 
    function() {
        var li = $(this).parents('li:first'),
        dl = $(this).parents('dl:first'),
        role = dl.attr('role'),
        tid = li.data('id'),
        eve = currentTools.data('events');
        switch ($(this).attr('role')) {
        case 'remove':
            currentTools.removeData('events');
            delete eve[role][li.data('events')][tid];
            if ($.isEmptyObject(eve[role][li.data('events')])) {
                delete eve[role][li.data('events')]
            };
            if ($.isEmptyObject(eve[role])) {
                delete eve[role]
            };
            if ($.isEmptyObject(eve)) {
                currentTools.removeAttr('data-events')
            } else {
                currentTools.attr('data-events', $.toJSON(eve))
            };
            change();
            if (!li.siblings().length) {
                dl.find('dt:first span').remove()
            };
            li.remove();
            resizeToolsScroll();
            break;
        case 'edit':
            addEvents(role, li.data('events'), eve[role][li.data('events')][tid], tid);
            break
        }
    });
    resetAddEvents();
    resizeToolsScroll()
};
function addEvents(role, events, topts, tid) {
    var eve = elEventsList[events],
    oHtml = '',
    eHtml = '',
    unitSelect = '<select role="unit" style="width:50px;"><option value="px">px</option><option value="%">%</option></select>';
    if (eve['el']) {
        if (eve['amniate']) {
            oHtml = '<tr>' + '<td valign="middle">动画效果：</td>' + '<td><select name="animations" style="width:300px;">';
            $.each(eve['amniate'], 
            function(i, item) {
                oHtml += '<option value="' + item + '">' + animations[item] + '</option>'
            });
            oHtml += '</select></td></tr>'
        };
        if (events == 'move') {
            eHtml += '<tr>' + '<td valign="middle">改变大小：</td>' + '<td>宽度&nbsp;<input name="width" type="text" class="inputText" role="css" style="width:50px;margin-right:-1px;">' + unitSelect + '&nbsp;&nbsp;高度&nbsp;<input name="height" type="text" class="inputText" role="css" style="width:50px;margin-right:-1px;">' + unitSelect + '</td>' + '</tr>' + '<tr>' + '<td valign="middle">移动位置：</td>' + '<td><div style="padding-left:65px;">上&nbsp;<input name="top" type="text" class="inputText" role="css" style="width:50px;margin-right:-1px;">' + unitSelect + '</div><div class="pt10">左&nbsp;<input name="left" type="text" class="inputText" role="css" style="width:50px;margin-right:-1px;">' + unitSelect + '&nbsp;&nbsp;<input name="right" type="text" class="inputText" role="css" style="width:50px;margin-right:-1px;">' + unitSelect + '&nbsp;右</div><div class="pt10" style="padding-left:65px;">下&nbsp;<input name="bottom" type="text" class="inputText" role="css" style="width:50px;margin-right:-1px;">' + unitSelect + '&nbsp;&nbsp;</div></td>' + '</tr>' + '<tr>' + '<td valign="middle">改变填充：</td>' + '<td><div style="padding-left:65px;">上&nbsp;<input name="padding-top" type="text" class="inputText" role="css" style="width:50px;margin-right:-1px;">' + unitSelect + '</div><div class="pt10">左&nbsp;<input name="padding-left" type="text" class="inputText" role="css" style="width:50px;margin-right:-1px;">' + unitSelect + '&nbsp;&nbsp;<input name="padding-right" type="text" class="inputText" role="css" style="width:50px;margin-right:-1px;">' + unitSelect + '&nbsp;右</div><div class="pt10" style="padding-left:65px;">下&nbsp;<input name="padding-bottom" type="text" class="inputText" role="css" style="width:50px;margin-right:-1px;">' + unitSelect + '&nbsp;&nbsp;</div></td>' + '</tr>' + '<tr>' + '<td valign="middle">改变间距：</td>' + '<td><div style="padding-left:65px;">上&nbsp;<input name="margin-top" type="text" class="inputText" role="css" style="width:50px;margin-right:-1px;">' + unitSelect + '</div><div class="pt10">左&nbsp;<input name="margin-left" type="text" class="inputText" role="css" style="width:50px;margin-right:-1px;">' + unitSelect + '&nbsp;&nbsp;<input name="margin-right" type="text" class="inputText" role="css" style="width:50px;margin-right:-1px;">' + unitSelect + '&nbsp;右</div><div class="pt10" style="padding-left:65px;">下&nbsp;<input name="margin-bottom" type="text" class="inputText" role="css" style="width:50px;margin-right:-1px;">' + unitSelect + '&nbsp;&nbsp;</div></td>' + '</tr>'
        } else if (events == 'zindex') {
            eHtml += '<tr>' + '<td valign="middle">元素层级：</td>' + '<td><input name="zindex" type="text" role="number" class="inputText" style="width:300px;"><div style="padding:10px 0;">输入0-100的数字</div></td>' + '</tr>'
        } else if (events == 'content') {
            eHtml += '<tr>' + '<td valign="middle">元素内容：</td>' + '<td><textarea name="content" class="inputText" style="width:300px;height:150px;resize:none; line-height:20px;"></textarea></td>' + '</tr>'
        };
        var el = $('<div id="eventsDialog" style="padding-bottom:50px;"><table width="100%" border="0" cellpadding="0" cellspacing="0" class="borderTable">' + '<tr>' + '<td valign="middle">元素ID：</td>' + '<td><input name="id" type="text" class="inputText" style="width:300px;"><div style="padding:10px 0;">元素ID可从元素属性里复制，<span class="pt10 ct_2">当前元素ID：' + currentToolsId + '</span></div></td>' + '</tr>' + oHtml + eHtml + '</table></div>');
        var getInputValue = function(group) {
            var obj = {};
            $('input[role="' + group + '"]', el).each(function() {
                if ($(this).val() != '') {
                    obj[$(this).attr('name')] = $(this).val() + $(this).next().val()
                }
            });
            return obj
        };
        top.ConfirmDialog(elEvents[role] + eve['name'], el, {
            onBeforeClose: function(fn, type) {
                if (type == 'confirm') {
                    var id = $('input[name="id"]', el).val(),
                    msg = '',
                    opts = {};
                    if (!id) {
                        msg = '请输入元素ID'
                    } else if (!$('#' + id, pageLayout).length) {
                        msg = '网页中没找到该元素ID'
                    } else if (events == 'move') {
                        opts['css'] = getInputValue('css');
                        if ($.isEmptyObject(opts['css'])) {
                            msg = '位置、大小和填充至少要填写一项'
                        }
                    } else if (events == 'zindex') {
                        var zIndex = $('input[name="zindex"]', el).val();
                        if (zIndex == '') {
                            msg = '层级必须填写'
                        } else if (opts > 100) {
                            msg = '层级不能大于100'
                        };
                        opts = {
                            zindex: zIndex
                        }
                    } else if (events == 'content') {
                        var content = $('textarea[name="content"]', el).val();
                        var rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
                        content = content.replace(rscript, "");
                        opts = {
                            content: content
                        }
                    };
                    if (msg) {
                        top.Alert(msg)
                    } else {
                        if (eve['amniate']) {
                            opts['animations'] = $('select[name="animations"]', el).val()
                        };
                        insertEvents(role, events, id, opts);
                        fn()
                    }
                } else {
                    fn()
                }
            },
            onConfirm: function() {}
        })
    };
    if (tid) {
        var setInputValue = function(key, value) {
            var units = '';
            if (value.indexOf('px') >= 0) {
                units = 'px'
            } else if (value.indexOf('%') >= 0) {
                units = '%'
            };
            if (units) {
                value = value.replace(units, '');
                $(':input[name="' + key + '"]', el).next().val(units)
            };
            $(':input[name="' + key + '"]', el).val(value)
        };
        $('input[name="id"]', el).val(tid).attr('disabled', true);
        if (typeof topts == 'object') {
            for (key in topts) {
                if (typeof topts[key] == 'object') {
                    for (key1 in topts[key]) {
                        setInputValue(key1, topts[key][key1])
                    }
                } else {
                    setInputValue(key, topts[key])
                }
            }
        }
    };
    top.$('#eventsDialog select').fancySelect({
        fancyClass: 'fancySelect1'
    })
};
function insertEvents(role, events, tid, opts) {
    var html = getEventLi(role, events, tid),
    dl = $('div[role="eventsContainer"] dl[role="' + role + '"]', toolsMain);
    if (!$('ul[role="eventsList"] li[data-id="' + tid + '"][data-events="' + events + '"]', dl).length) {
        $('ul[role="eventsList"]', dl).append(html);
        if (!dl.find('i.setNewIcon').length) {
            dl.find('dt:first').append('<span class="fr pt5"><i class="setNewIcon"></i></span>')
        }
    };
    var eve = currentTools.data('events');
    if (!eve) {
        eve = {}
    } else {
        currentTools.removeData('events')
    };
    if (!eve[role]) {
        eve[role] = {}
    };
    if (!eve[role][events]) {
        eve[role][events] = {}
    };
    eve[role][events][tid] = opts;
    currentTools.attr('data-events', $.toJSON(eve));
    change();
    resizeToolsScroll()
};
function getEventLi(role, events, tid) {
    return '<li class="clearfix" data-events="' + events + '" data-id="' + tid + '" role="eventsLi">' + elEventsList[events]['name'] + '：&nbsp;<span class="fr"><a href="javascript:;" class="ct_2" role="edit"><span class="icon-pencil"></span></a>&nbsp;&nbsp;<a href="javascript:;" class="ct_2" role="remove"><span class="icon-remove"></span></a></span><br>' + tid + '</li>'
};
function resetAddEvents() {
    var container = $('div[role="eventsContainer"]', toolsMain);
    if (!container.length) return;
    $('ul[role="eventsList"]', container).empty();
    $('i.setNewIcon', container).parent().remove();
    var eve = currentTools.data('events');
    if (eve) {
        for (role in eve) {
            for (events in eve[role]) {
                for (tid in eve[role][events]) {
                    var li = getEventLi(role, events, tid);
                    $('dl[role="' + role + '"] ul[role="eventsList"]', container).append(li)
                }
            }
        }
    };
    $('dl', container).each(function() {
        if ($('li[role="eventsLi"]', $(this)).length) {
            $(this).find('dt:first').append('<span class="fr pt5"><i class="setNewIcon"></i></span>')
        }
    })
};
function getElTree() {
    var data = [],
    getChildren = function(el, cdata) {
        $('>div,>#header,>#footer', el).each(function() {
            var tdata = cdata,
            item = $(this);
            if (item.attr('path') && item.attr('id')) {
                var path = item.attr('path'),
                name = '';
                if (path == 'app') {
                    name = item.data('data').name
                } else {
                    name = pathName[path]
                };
                var idata = {
                    title: name + ' ' + item.attr('id'),
                    isFolder: true,
                    key: item.attr('id'),
                    expand: true,
                    hideCheckbox: false,
                    children: []
                };
                cdata.push(idata);
                tdata = idata.children
            };
            if ($('div[path]', item).length) {
                getChildren(item, tdata)
            }
        })
    };
    getChildren(pageLayout, data);
    return data
};
function getElToolsData() {
    var data = [],
    path = selectedTools.attr('path'),
    properties = {
        "name": "属性",
        "toolsTop": "",
        "toolsFoot": "",
        "html": "<div role='properties'></div>",
        "init": getProperties
    },
    events = {
        "name": "交互",
        "toolsTop": "",
        "toolsFoot": "",
        "html": "<div class='h6 ct_2'>设置元素的交互事件</div><div role='eventsContainer'></div>",
        "init": getEvents
    },
    moreStyle = {},
    topHtml = '<ul class="clearfix" data-selector="">' + styleToolsTop + '</ul>',
    footHtml = '',
    selectHtml = '<li class="active" data-selector=""><i class="icon-checkmark"></i>模块整体</li>',
    styleContainerHtml = '<div role="styleContainer" data-selector=""></div>';
    if (path == 'app') {
        if (selectedTools.data('type') == 'app') {
            moreStyle = {
                '.con_header': '模块头部',
                '.appTitle  h2': '模块标题',
                '.appMore': '模块更多',
                '.con_body': '模块主体',
                '.con_footer': '模块底部'
            }
        };
        if (selectedTools.data('data') && selectedTools.data('data')['selector']) {
            $.extend(true, moreStyle, selectedTools.data('data')['selector'])
        };
        for (key in moreStyle) {
            selectHtml += '<li data-selector="' + key + '"><i class="icon-checkmark"></i>' + moreStyle[key] + '</li>';
            topHtml += '<ul class="clearfix" data-selector="' + key + '" style="display:none;">' + styleToolsTop + '</ul>';
            styleContainerHtml += '<div role="styleContainer" data-selector="' + key + '" style="display:none;"></div>'
        };
        if (!$.isEmptyObject(moreStyle)) {
            footHtml = '<div class="h6 moreSetStyle"><div class="setSelectMain"><ul>' + selectHtml + '</ul></div>更多局部样式&nbsp;&nbsp;<i class="trigon top ct_3 mt5 small"></i></div>'
        }
    };
    data = [properties, {
        "name": "样式",
        "toolsTop": topHtml,
        "toolsFoot": footHtml,
        "html": styleContainerHtml,
        "init": function() {
            $('div[role="toolsFoot"]', toolsMain).delegate('div.moreSetStyle', click, 
            function() {
                $(this).toggleClass('active')
            }).delegate('li', click, 
            function() {
                if ($(this).hasClass('active')) return;
                var selector = $(this).data('selector'),
                sContainer = $('div[role="styleContainer"][data-selector="' + selector + '"]', toolsMain),
                sTab = $('div[role="toolsTop"] ul[data-selector="' + selector + '"]', toolsMain);
                sContainer.show().siblings().hide();
                sTab.show().siblings().hide();
                $(this).toActive();
                if (!sContainer.children().length) {
                    setElStyle(selectedTools, selector, $(this).text())
                };
                resizeToolsScroll()
            });
            setElStyle(selectedTools, '', '模块整体');
            if (!$.isEmptyObject(moreStyle)) {
                resetMoreStyle()
            }
        }
    }];
    if (path == 'app' && selectedTools.data('data')['stylesList']) {
        data.push({
            "name": "排版",
            "toolsTop": "",
            "toolsFoot": "",
            "html": "<div role='appLayoutContainer'></div>",
            "init": getAppLayout
        })
    };
    data.push(events);
    return data
};
function resetMoreStyle() {
    if (currentToolsId == 'body') return;
    if ($('div.moreSetStyle li', toolsMain).length) {
        $('div.moreSetStyle li', toolsMain).each(function() {
            if (!$('#' + currentToolsId + ' ' + $(this).data('selector'), pageBody).length) {
                $(this).hide();
                if ($(this).hasClass('active')) {
                    $('div.moreSetStyle li:first', toolsMain).trigger(click)
                }
            } else {
                $(this).show()
            }
        })
    }
};